<template>
  <div class="echarts">
    <div id="barchart" style="width: 800px; height: 450px"></div>
  </div>
</template>

<script>
import echarts from "echarts";
export default {
    name:"barCharts",
    data() {
      return {
        xData:[],
        yData:[],
      }
    },
    props:{
      datar:{type:Array}
    },
    watch: {
      datar: function (val) {
        if (val.length > 0) {
          this.xData = [],
          this.yData = [],
          this.mycharts()
        }
      },
    },

    methods: {
    mycharts() {
      var myChart = echarts.init(document.getElementById("barchart"));
      //   配置图表
      var option = {
        toolbox: {
          show: true,
          itemSize:20,
          itemGap:15,
          feature: {
            dataZoom: {
              yAxisIndex: "none",
            },
            dataView: {
              readOnly: true,
            },
            magicType: {
              type: ["line", "bar"],
            },
            restore: {},  //还原
            saveAsImage: {},  //保存为图片
          },
        },
        title: {
          text: "库存条状图",
        },

        tooltip: {},
        grid:{
          x:40,
          y:60,
          y2:20,
          x2:20,
        },
        legend: {
          data: ["库存量"],
        },
        xAxis: {
          data: this.xData,
          axisLabel:{
            textStyle:{
              fontSize:10,
              fontWeight:"bold",
            },
            interval:0,   //横轴信息全部显示
          }
        },
        yAxis: {},
        series: [
          {
            name: "库存量",
            type: "bar",
            data: this.yData,
            showBackground: true,
            backgroundStyle: {
              color: "rgba(180, 180, 180, 0.2)",
            },
            itemStyle: {
              normal: {
                color: function (params) {
                  var colorList = [
                    "#0780CF",
                    "#FA6D1D",
                    "#AC2026",
                    "#701866",
                    "#D22E8D",
                    "#FE8463",
                    "#A195C5",
                    "#FAD860",
                    "#F3A43B",
                  ];
                  return colorList[params.dataIndex];
                },
                label: {
                  show: true,
                  position: "top",
                  formatter: "{b}\n{c}",
                },
              },
            },
          },
        ],
      };
      this.datar.forEach(item=>{
        console.log(item)
        this.xData.push(item.name)
        this.yData.push(item.stock)
      })
      myChart.setOption(option);
    },
  },
  mounted() {
    this.mycharts();
    console.log(this.datar)
  },
};
</script>

<style lang="less" scoped>
</style>